package com.windliven.spoc.modules.init.controller;

import com.alibaba.fastjson.JSONObject;
import com.windliven.spoc.modules.init.common.ApiResponse;
import com.windliven.spoc.modules.init.common.BizEnum;
import com.windliven.spoc.modules.init.exception.BizException;
import com.windliven.spoc.modules.init.param.WeiXinParam;
import com.windliven.spoc.modules.init.utils.WeixinLoginUtils;
import com.windliven.spoc.modules.init.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author sunboyuan
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @PostMapping("/loginByApp")
    public ApiResponse loginByApp(LoginVo loginVo) {

        if (StringUtils.isBlank(loginVo.getCode())) {
            throw new BizException(BizEnum.INVALID_PARAM);
        }

        try {
            StringBuilder sb = WeixinLoginUtils.getAccessTokenBycode("", "", loginVo.getCode());
            if (sb != null) {
                if (sb.toString().trim().contains("errcode")) {
                    return ApiResponse.ofError();
                }
                JSONObject object = JSONObject.parseObject(sb.toString().trim());
                String accessToken = object.getString("access_token");
                String openID = object.getString("openid");
                //获取微信用户基本信息
                WeiXinParam appWeiXinUserInfo = WeixinLoginUtils.getAppWeiXinUserInfo(accessToken, openID, WeiXinParam.class);



                return ApiResponse.ofSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ApiResponse.ofSuccess();
    }
}
